package services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Category;
import model.Item;
import model.Member;
import utils.WebUtils;
import core.Lookup;
import core.ManagerLocal;
import core.MemberManagerLocal;


public class RemoveCategory extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		process(req,resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		Integer idCategory = WebUtils.safeGetParameterInteger(req, "idCategory");
		
		String memberCellphone = WebUtils.safeGetParameterString(req, "memberCellphone");
		String memberEmail = WebUtils.safeGetParameterString(req, "memberEmail");
		String memberPassword = WebUtils.safeGetParameterString(req, "memberPassword");
		
		
		if(idCategory == null){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "idCategory parameter is required");
			return;
		}

		ManagerLocal manager = Lookup.lookupManager();
		MemberManagerLocal memberManager = Lookup.lookupMemberManager();
		
		Member member = memberManager.loginMember(memberCellphone, memberEmail, memberPassword);
		
		if(member == null || !member.isSuperAdmin()){
			resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "not authorized");
			return;	
		}
		
		Category category = manager.get(Category.class, idCategory);
		
		if(category == null){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "category not found");
			return;
		}
		
		List<Category> subcategories = manager.listCategory(null, idCategory);
		
		if(!subcategories.isEmpty()){
			resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "Please remove subcategories before");
			return;
		}

		List<Item> subitems = manager.listItems(member, idCategory);
		
		if(!subitems.isEmpty()){
			resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "Please remove subitems before");
			return;
		}
		
		manager.remove(Category.class, idCategory);
		
		String outputString = "{success: true}";	
		
		PrintWriter writer = resp.getWriter();
		resp.setContentType("text/html;charset=UTF-8");
		writer.print(outputString);
		writer.close();
	}
	
	

	

}
